import { RECORD_ADDRESS, SAVE_ADDRESS, ADD_CART, REDUCE_CART } from './actionTypes'

export default {
    state: {
        latitude: '',
        longitude: '',
        removeAddress: [],
        cartList: {} // 加入购物车的商品列表
    },
    getters: {
        latitude: state => state.latitude,
        longitude: state => state.longitude,
        cartList: state => state.cartList,
    },
    mutations: {
        // 记录当前经度纬度
        [RECORD_ADDRESS](state, { latitude, longitude }) {
            state.latitude = latitude;
            state.longitude = longitude;
        },
        // [SAVE_ADDRESS](state, newAdress) {
        //     state.removeAddress = newAdress
        // },
        [ADD_CART](state, cartList) {
            state.cartList = cartList;
            //存入localStorage
            // setStore('buyCart', state.cartList);
        },
        [REDUCE_CART](state, cartList) {
            state.cartList = cartList;
            //存入localStorage
            // setStore('buyCart', state.cartList);
        },
    },
    actions: {
        [RECORD_ADDRESS]({ commit, state }, xy) {
            commit('RECORD_ADDRESS', xy)
        },
        // [SAVE_ADDRESS]({ commit, state }, address) {
        //     commit('SAVE_ADDRESS', address)
        // },
        [ADD_CART]({ commit, state }, { shopid, category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock }) {
            let cart = state.cartList; // 购物车列表
            let shop = cart[shopid] = (cart[shopid] || {});
            let category = shop[category_id] = (shop[category_id] || {});
            let item = category[item_id] = (category[item_id] || {});
            if (item[food_id]) {
                item[food_id]['num']++
            } else {
                item[food_id] = {
                    'num': 1,
                    'id': food_id,
                    'name': name,
                    'price': price,
                    'specs': specs,
                    'packing_fee': packing_fee,
                    'sku_id': sku_id,
                    'stock': stock
                }
            }

            let cartList = { ...cart };
            commit('ADD_CART', cartList)
        },
        [REDUCE_CART]({ commit, state }, { shopid, category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock }) {
            let cart = state.cartList;
            let shop = (cart[shopid] || {});
            let category = (shop[category_id] || {});
            let item = (category[item_id] || {});
            if (item && item[food_id]) {
                if (item[food_id]['num'] > 0) {
                    item[food_id]['num']--;
                    let cartList = { ...cart };
                    commit('REDUCE_CART', cartList)
                } else {
                    //商品数量为0，则清空当前商品的信息
                    item[food_id] = null;
                }
            }
        }
    }
}